<template>
  <div class="app-container">
    <el-card shadow="never">
      <div slot="header" class="clearfix">
        <span>{{ title }}</span>
        <el-button
          style="float: right; margin-left: 10px"
          type="primary"
          @click="handleSave"
        >保存试卷
        </el-button>
        <el-button
          style="float: right"
          type="success"
          @click="handlePreview"
        >预览试卷
        </el-button>
      </div>

      <!-- 试卷基本信息 -->
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="试卷标题" prop="title">
              <el-input v-model="form.title" placeholder="请输入试卷标题"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="试卷编码" prop="code">
              <el-input v-model="form.code" placeholder="请输入试卷编码"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="总分">
              <el-input-number
                v-model="form.totalScore"
                :precision="2"
                :step="1"
                :min="0"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="及格分">
              <el-input-number
                v-model="form.passScore"
                :precision="2"
                :step="1"
                :min="0"
                :max="form.totalScore"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="考试时长(分)">
              <el-input-number
                v-model="form.timeLimit"
                :step="5"
                :min="0"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="试卷说明">
          <el-input
            v-model="form.remark"
            type="textarea"
            :rows="2"
            placeholder="请输入试卷说明"
          />
        </el-form-item>
      </el-form>

      <!-- 题目列表 -->
      <div class="question-list-header">
        <el-button type="primary" icon="el-icon-plus" @click="showQuestionSelector = true">
          添加题目
        </el-button>
        <span class="question-count">共 {{ form.questions.length }} 题</span>
        <span class="total-score">总分：{{ form.totalScore }} 分</span>
      </div>

      <el-table
        :data="form.questions"
        border
        style="width: 100%"
        row-key="id"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"/>
        <el-table-column prop="sort" label="序号" width="80">
          <template slot-scope="scope">
            <el-input-number
              v-model="scope.row.sort"
              :min="1"
              :step="1"
              @change="sortQuestions"
            />
          </template>
        </el-table-column>
        <el-table-column prop="typeName" label="题型" width="120"/>
        <el-table-column prop="title" label="题目" min-width="300">
          <template slot-scope="scope">
            <div v-html="scope.row.title" class="question-title"></div>
          </template>
        </el-table-column>
        <el-table-column prop="score" label="分值" width="120">
          <template slot-scope="scope">
            <el-input-number
              v-model="scope.row.score"
              :min="0.5"
              :step="0.5"
              :precision="1"
              @change="calculateTotalScore"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              @click="handleEditQuestion(scope.$index, scope.row)"
            >编辑
            </el-button>
            <el-button
              size="mini"
              type="text"
              style="color: #f56c6c"
              @click="handleRemoveQuestion(scope.$index, scope.row)"
            >删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 题目选择对话框 -->
    <el-dialog
      title="选择题目"
      :visible.sync="showQuestionSelector"
      width="80%"
      top="5vh"
      append-to-body
    >
      <question-selector
        ref="questionSelector"
        :selected-questions="selectedQuestionIds"
        @confirm="handleSelectQuestions"
      />

    </el-dialog>

    <!-- 试卷预览对话框 -->
    <el-dialog
      title="试卷预览"
      :visible.sync="showPreviewDialog"
      width="80%"
      top="5vh"
      append-to-body
    >
      <paper-preview
        v-if="showPreviewDialog"
        :paper="previewData"
        @edit-question="handleEditQuestionFromPreview"
        ref="paperPreview"
      />
      <div slot="footer" class="dialog-footer">
        <el-button @click="showPreviewDialog = false">关闭</el-button>
        <el-dropdown @command="handleExport" class="ml-10">
          <el-button type="primary">
            导出试卷<i class="el-icon-arrow-down el-icon--right"></i>
          </el-button>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item command="pdf">导出为PDF</el-dropdown-item>
            <el-dropdown-item command="word">导出为Word</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </div>
    </el-dialog>

    <!-- 题目编辑对话框 -->
    <el-dialog
      :title="editDialogTitle"
      :visible.sync="showEditDialog"
      width="70%"
      top="5vh"
      append-to-body
    >
      <question-edit-form
        v-if="showEditDialog"
        :question="currentQuestion"
        :paper-question="currentPaperQuestion"
        @save="handleSaveQuestion"
      />
    </el-dialog>
  </div>
</template>

<script>
import {createPaper, updatePaper, getPaperDetail, previewPaper, exportPaper} from '@/api/paper2/paper'
import QuestionSelector from './QuestionSelector'
import PaperPreview from './PaperPreview'
import QuestionEditForm from './QuestionEditForm'
import FormulaRenderer from "@/components/FormulaRenderer/index.vue";

export default {
  name: 'ManualPaper',
  components: {FormulaRenderer, QuestionSelector, PaperPreview, QuestionEditForm},
  data() {
    return {
      title: '手动组卷',
      form: {
        id: null,
        title: '',
        code: '',
        totalScore: 0,
        passScore: null,
        timeLimit: null,
        remark: '',
        questions: []
      },
      rules: {
        title: [{required: true, message: '请输入试卷标题', trigger: 'blur'}],
        code: [{required: true, message: '请输入试卷编码', trigger: 'blur'}]
      },
      showQuestionSelector: false,
      showPreviewDialog: false,
      showEditDialog: false,
      previewData: null,
      selectedQuestionIds: [],
      currentQuestion: null,
      currentPaperQuestion: null,
      editDialogTitle: '编辑题目',
      multipleSelection: []
    }
  },
  created() {
    const paperId = this.$route.query.id
    if (paperId) {
      this.title = '编辑试卷'
      this.loadPaper(paperId)
    }
  },
  methods: {
    loadPaper(paperId) {
      getPaperDetail(paperId).then(response => {
        const data = response.data
        this.form = {
          id: data.id,
          title: data.title,
          code: data.code,
          totalScore: data.totalScore,
          passScore: data.passScore,
          timeLimit: data.timeLimit,
          remark: data.remark,
          questions: data.questions
        }
        this.selectedQuestionIds = data.questions.map(q => q.questionId)
      })
    },
    handleSave() {
      this.$refs.form.validate(valid => {
        if (valid) {
          const saveData = {
            ...this.form,
            questions: this.form.questions.map(q => ({
              questionId: q.questionId,
              score: q.score,
              sort: q.sort,
              required: q.required || 1
            }))
          }

          const savePromise = this.form.id
            ? updatePaper(saveData)
            : createPaper(saveData)

          savePromise.then(response => {
            this.$message.success('保存成功')
            if (!this.form.id) {
              this.$router.push({path: '/paper2/manual', query: {id: response.data}})
            }
          })
        }
      })
    },
    handlePreview() {
      if (this.form.questions.length === 0) {
        this.$message.warning('请先添加题目')
        return
      }

      // 获取预览选项
      const previewOptions = this.$refs.paperPreview ?
        this.$refs.paperPreview.previewOptions : null

      // 如果是编辑已有试卷，从服务器获取最新预览数据
      if (this.form.id) {
        previewPaper(this.form.id, previewOptions).then(response => {
          this.previewData = response.data
          console.log('response.data',response.data)
          this.showPreviewDialog = true
        })
      } else {
        // 新建试卷，使用当前数据预览
        this.previewData = {
          ...this.form,
          questionsByType: this.groupQuestionsByType(this.form.questions),
          previewOptions: previewOptions || {
            showAnswers: true,
            showOptionAnswers: true,
            showAnalysis: true,
            showKnowledgePoints: true,
            showDifficulty: true
          }
        }
        this.showPreviewDialog = true
      }
    },

    groupQuestionsByType(questions) {
      const grouped = {}
      questions.forEach(q => {
        if (!grouped[q.typeName]) {
          grouped[q.typeName] = []
        }
        grouped[q.typeName].push(q)
      })
      return grouped
    },
    handleExport(command) {
      if (!this.form.id) {
        this.$message.warning('请先保存试卷')
        return
      }

      // 获取当前的预览选项
      const previewOptions = this.$refs.paperPreview.previewOptions
      const _command = (command === 'pdf'? 'pdf' : 'docx')
      // const _type = (command === 'pdf'? 'application/octet-stream' : 'application/vnd.openxmlformats-officedocument.wordprocessingml.document')
      const _type = (command === 'pdf'? 'application/octet-stream' : 'application/octet-stream')
      console.log('导出文件类型:',_command)
      console.log('文件流类型:',_type)
      exportPaper(this.form.id, command, previewOptions).then(response => {
        console.log('response\n',response);
        const blob = new Blob([response], {
          type: _type
        })
        const url = window.URL.createObjectURL(blob)
        const link = document.createElement('a')
        link.href = url

        link.download = `${this.form.title}_${new Date().toLocaleString()}.${_command}`
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        window.URL.revokeObjectURL(url)
      })
    },
    handleSelectQuestions(selectedQuestions) {
      // 合并已选题目
      const newQuestions = selectedQuestions.filter(q =>
        !this.selectedQuestionIds.includes(q.id)
      )

      if (newQuestions.length > 0) {
        const questionsToAdd = newQuestions.map(q => ({
          questionId: q.id,
          title: q.title,
          typeName: q.typeName,
          score: 5, // 默认分值
          sort: this.form.questions.length + 1,
          required: 1
        }))

        this.form.questions = [...this.form.questions, ...questionsToAdd]
        this.selectedQuestionIds = [...this.selectedQuestionIds, ...newQuestions.map(q => q.id)]
        this.calculateTotalScore()
      }

      this.showQuestionSelector = false
    },
    handleRemoveQuestion(index, row) {
      this.$confirm('确定要移除此题目吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.form.questions.splice(index, 1)
        this.selectedQuestionIds = this.selectedQuestionIds.filter(id => id !== row.questionId)
        this.calculateTotalScore()
        this.$message.success('移除成功')
      })
    },
    handleEditQuestion(index, row) {
      this.currentQuestion = {...row}
      this.currentPaperQuestion = {...row}
      this.editDialogTitle = `编辑题目 - ${row.typeName}`
      this.showEditDialog = true
    },
    handleEditQuestionFromPreview(question) {
      const index = this.form.questions.findIndex(q => q.questionId === question.questionId)
      if (index >= 0) {
        this.handleEditQuestion(index, this.form.questions[index])
      }
    },
    handleSaveQuestion(updatedQuestion) {
      const index = this.form.questions.findIndex(q => q.questionId === updatedQuestion.questionId)
      if (index >= 0) {
        this.form.questions.splice(index, 1, {
          ...this.form.questions[index],
          ...updatedQuestion
        })
        this.calculateTotalScore()
      }
      this.showEditDialog = false
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    sortQuestions() {
      // 根据sort字段重新排序
      this.form.questions.sort((a, b) => a.sort - b.sort)
    },
    calculateTotalScore() {
      this.form.totalScore = this.form.questions.reduce((sum, q) => sum + q.score, 0)
      if (this.form.passScore > this.form.totalScore) {
        this.form.passScore = this.form.totalScore
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.question-list-header {
  margin-bottom: 15px;
  display: flex;
  align-items: center;

  .question-count {
    margin-left: 20px;
    font-size: 14px;
    color: #666;
  }

  .total-score {
    margin-left: 20px;
    font-size: 14px;
    color: #409EFF;
    font-weight: bold;
  }
}

.question-title {
  ::v-deep img {
    max-width: 100%;
    height: auto;
  }

  ::v-deep .editor-content-view {
    border: 3px solid #ccc;
    border-radius: 5px;
    padding: 0 10px;
    margin-top: 20px;
    overflow-x: auto;
  }

  ::v-deep .editor-content-view p,
  ::v-deep .editor-content-view li {
    white-space: pre-wrap;
  }

  ::v-deep .editor-content-view blockquote {
    border-left: 8px solid #d0e5f2;
    padding: 10px 10px;
    margin: 10px 0;
    background-color: #f1f1f1;
  }

  ::v-deep .editor-content-view code {
    font-family: monospace;
    background-color: #eee;
    padding: 3px;
    border-radius: 3px;
  }

  ::v-deep .editor-content-view pre > code {
    display: block;
    padding: 10px;
  }

  ::v-deep .editor-content-view table {
    border-collapse: collapse;
  }

  ::v-deep .editor-content-view td,
  ::v-deep .editor-content-view th {
    border: 1px solid #ccc;
    min-width: 50px;
    height: 20px;
  }

  ::v-deep .editor-content-view th {
    background-color: #f1f1f1;
  }

  ::v-deep .editor-content-view ul,
  ::v-deep .editor-content-view ol {
    padding-left: 20px;
  }

  ::v-deep .editor-content-view input[type="checkbox"] {
    margin-right: 5px;
  }
}
</style>
